// generated on 2016-07-26 using generator-webapp 2.1.0

const gulp = require('gulp');
var connect = require('gulp-connect');
const gulpLoadPlugins = require('gulp-load-plugins');
const browserSync = require('browser-sync');
const del = require('del');
const wiredep = require('wiredep').stream;
const babelpolyfill = require("babel-polyfill");
require("babel-loader");

const $ = gulpLoadPlugins();
const reload = browserSync.reload;

gulp.task('styles', () => {
    return gulp.src('app/styles/*.css')
        .pipe($.sourcemaps.init())
        .pipe($.autoprefixer({
            browsers: ['> 1%', 'last 2 versions', 'Firefox ESR']
        }))
        .pipe($.sourcemaps.write())
        .pipe(gulp.dest('.tmp/styles'))
        .pipe(reload({
            stream: true
        }));
});

gulp.task('scripts', () => {
    return gulp.src('app/scripts/**/*.js')
        .pipe($.plumber())
        .pipe($.sourcemaps.init())
        // .pipe($.babel({
        //     presets: ['es2015', "stage-0"],
        // }))
        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest('.tmp/scripts'))
        .pipe(reload({
            stream: true
        }));
});

function lint(files, options) {
    return gulp.src(files)
        .pipe(reload({
            stream: true,
            once: true
        }))
        .pipe($.eslint(options))
        .pipe($.eslint.format())
        .pipe($.if(!browserSync.active, $.eslint.failAfterError()));
}

gulp.task('lint', () => {
    return lint('app/scripts/**/*.js', {
        fix: true
    })
        .pipe(gulp.dest('app/scripts'));
});
gulp.task('lint:test', () => {
    return lint('test/spec/**/*.js', {
        fix: true,
        env: {
            mocha: true
        }
    })
        .pipe(gulp.dest('test/spec/**/*.js'));
});

gulp.task('html', ['styles', 'scripts'], () => {
    return gulp.src('app/*.html')
        .pipe($.useref({
            searchPath: ['.tmp', 'app', '.']
        }))
        .pipe($.if('*.js', $.uglify()))
        .pipe($.if('*.css', $.cssnano({
            safe: true,
            autoprefixer: false
        })))
        .pipe($.if('*.html', $.htmlmin({
            collapseWhitespace: true
        })))
        .pipe(gulp.dest('dist'))
});
gulp.task('sc', function() {
    return gulp.src('dist/scripts/**/*.js')
        .pipe($.rev())
        .pipe(gulp.dest('dist/scripts'))
        .pipe($.rev.manifest())
        .pipe(gulp.dest('rev/js'));
});
gulp.task('st', function() {
    var dist = gulp.src('dist/styles/**/*.css');
    return dist
        .pipe($.rev())
        .pipe(gulp.dest('dist/styles'))
        .pipe($.rev.manifest())
        .pipe(gulp.dest('rev/css'));
});

gulp.task('rev', ['sc', 'st'], () => {
    return gulp.src(['./rev/**/*.json', 'dist/**/*.html']) //- 读取 rev-manifest.json 文件以及需要进行css名替换的文件

        .pipe($.revCollector({
            replaceReved: true,
            dirReplacements: {
            }
        })) //- 执行文件内css名的替换

        .pipe(gulp.dest('./dist/')); //- 替换后的文件输出的目录

});


gulp.task('images', () => {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            progressive: true,
            interlaced: true,
            // don't remove IDs from SVGs, they are often used

            // as hooks for embedding and styling

            svgoPlugins: [{
                cleanupIDs: false
            }]
        })))
        .pipe(gulp.dest('dist/images'));
});

gulp.task('fonts', () => {
    return gulp.src(require('main-bower-files')('**/*.{eot,svg,ttf,woff,woff2}', function(err) {})
        .concat('app/fonts/**/*'))
        .pipe(gulp.dest('.tmp/fonts'))
        .pipe(gulp.dest('dist/fonts'));
});
gulp.task('assets', () => {
    return gulp.src([
        'app/assets/**/*.*',
    ], {
        dot: true
    }).pipe(gulp.dest('dist/assets'));
});

gulp.task('extras', () => {
    return gulp.src([
        'app/*.*',
        '!app/*.html'
    ], {
        dot: true
    }).pipe(gulp.dest('dist'));
});

gulp.task('clean', del.bind(null, ['.tmp', 'dist', 'rev', 'distpush']));

gulp.task('webserver', function() {
    connect.server({
        port: 8080,
        root: ['app'],
        host: 'starfans.ai-muta.com/',
        middleware: function(connect) {
            return [connect().use('/bower_components', connect.static('bower_components'))];
        }
    });
});
gulp.task('webserver:dist', function() {
    connect.server({
        port: 8080,
        root: ['dist'],
        host: 'starfans.ai-muta.com/',
        middleware: function(connect) {
            return [connect().use('/bower_components', connect.static('bower_components'))];
        }
    });
});


gulp.task('serve', ['styles', 'scripts', 'fonts'], () => {
    // browserSync({

    //   notify: false,

    //   port: 80,

    //   server: {

    //     baseDir: ['app'],

    //     routes: {

    //       '/bower_components': 'bower_components'

    //     }

    //   }

    // });


    browserSync({
        notify: false,
        port: 8099,
        server: {
            baseDir: ['.tmp', 'app'],
            routes: {
                '/bower_components': 'bower_components'
            }
        }
    });

    gulp.watch([
        'app/*.html',
        'app/images/**/*',
        '.tmp/fonts/**/*'
    ]).on('change', reload);

    gulp.watch('app/styles/**/*.css', ['styles']).on('change', reload);
    gulp.watch('app/scripts/**/*.js', ['scripts']).on('change', reload);
    gulp.watch('app/fonts/**/*', ['fonts']).on('change', reload);
    gulp.watch('bower.json', ['wiredep', 'fonts']).on('change', reload);
});

gulp.task('serve:dist', () => {
    browserSync({
        notify: false,
        port: 8099,
        server: {
            baseDir: ['dist']
        }
    });
});

gulp.task('serve:test', ['scripts'], () => {
    browserSync({
        notify: false,
        port: 8099,
        ui: false,
        server: {
            baseDir: 'test',
            routes: {
                '/scripts': '.tmp/scripts',
                '/bower_components': 'bower_components'
            }
        }
    });

    gulp.watch('app/scripts/**/*.js', ['scripts']);
    gulp.watch('test/spec/**/*.js').on('change', reload);
    gulp.watch('test/spec/**/*.js', ['lint:test']);
});

// inject bower components

gulp.task('wiredep', () => {
    gulp.src('app/*.html')
        .pipe(wiredep({
            exclude: ['bootstrap.js'],
            ignorePath: /^(\.\.\/)*\.\./
        }))
        .pipe(gulp.dest('app'));
});

gulp.task('build', ['lint', 'html', 'images', 'fonts', 'extras','assets'], () => {
    gulp.start('rev');
    return gulp.src('dist/**/*').pipe($.size({
        title: 'build',
        gzip: true
    }));
});

gulp.task('default', ['clean'], () => {
    gulp.start('build');
});